import AudioManager from "./AudioManager";
import Banner from "./Banner";
import { BundleManager } from "./BundleManager";
import GameData, { EarthOut } from "./GameData";
import Build from "./Gwx/Build";
import Earth from "./Gwx/Earth";
import WTool, { TweenType } from "./WTool";
import { ZTool } from "./ZTool";

const { ccclass, property } = cc._decorator;



@ccclass
export default class GameManager extends cc.Component {
    @property(cc.Node)
    GameUI: cc.Node = null;
    @property(cc.Node)
    MainUI: cc.Node = null;
    @property(cc.Node)//地球节点
    EarthNode: cc.Node = null;
    @property(cc.Camera)//主摄像机
    mainCamera: cc.Camera = null;
    @property(cc.Node)
    Bg: cc.Node = null;
    @property(cc.Node)
    TouchEvent: cc.Node = null;
    @property(cc.Node)
    Touch: cc.Node = null;

    public plantMode: boolean = false;//种植模式
    public plantId: number = 0;//种植ID

    public GamePause: boolean = false;//游戏暂停

    public GameScore: number = 0;

    public static IsGuided: boolean = false;//引导完成
    public GuideIndex: number = 0;//引导索引

    private static _instance: GameManager = null;
    public static get Instance(): GameManager {
        if (!this._instance) {
            this._instance = new GameManager();
        }
        return this._instance;
    }

    protected onLoad(): void {
        GameData.InitData();
        GameManager._instance = this;
        cc.director.getCollisionManager().enabled = true;
        cc.director.getPhysicsManager().enabled = true;
        cc.director.getPhysicsManager().debugDrawFlags = 1;
    }

    start() {
        this.Init();
        if (!Banner.IsBlackWhite) {//正常包模式
            Banner.Instance.ShowNativeAd();
            Banner.Instance.ShowBanner();
        } else {//黑白包模式
            if (Banner.cityIswhite) {//黑包
                Banner.Instance.ShowVideo(() => { });
                Banner.Instance.ShowNativeAd();
                Banner.Instance.ShowBanner();
            } else {//白包
                Banner.Instance.ShowNativeAd();
                Banner.Instance.ShowBanner();
            }
        }

        this.Touch.active = false;
        this.TouchEvent.on(cc.Node.EventType.TOUCH_START, (e: cc.Touch) => {
            this.Touch.active = true;
            WTool.setWorldPos(this.Touch, cc.v2(e.getLocation().x, e.getLocation().y));
            if (this.plantMode == true) {//种植模式
                this.plant(this.plantId, Math.floor(this.GetRotaTionId(e)));
                this.plantMode = false;
                this.GameUI.getChildByName("Builds").active = true;
                //刷新这个UI
            }
            else {
                if (this.GameUI.active) AudioManager.PlayEffect("单击");
            }
        })
        this.TouchEvent.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Touch) => {
            this.Touch.active = true;
            WTool.setWorldPos(this.Touch, cc.v2(e.getLocation().x, e.getLocation().y));
        })
        this.TouchEvent.on(cc.Node.EventType.TOUCH_END, (e: cc.Touch) => {
            this.Touch.active = false;
        })
        this.TouchEvent.on(cc.Node.EventType.TOUCH_CANCEL, (e: cc.Touch) => {
            this.Touch.active = false;
        })
    }
    //秒事件
    secondincident() {
        this.C_Money(GameData.Instance.increaseSpeed * GameData.Instance.increasemultiple);
    }
    //5秒事件
    Fivesecondincident() {
        if (GameData.Instance.GameScore > 5000) {
            this.Createlightning();//生成闪电
        }
    }
    //初始化场景
    Init() {
        this.GameUI.active = false;
        this.MainUI.active = true;
        this.JudgeMoneyEnough();
        AudioManager.PlayMusic("前半段");
    }
    /**游戏结束 */
    GameOver(IsWin: boolean) {
        if (IsWin) {

        } else {
            //失败
            this.GameUI.getChildByName("Energy").active = false;
            this.GameUI.getChildByName("Builds").active = false;
            this.GameUI.getChildByName("视屏").active = false;
            this.Camera_shake(() => {
                this.EarthNode.removeAllChildren();
                if (!Banner.IsBlackWhite) {//正常包模式
                    Banner.Instance.ShowNativeAd();
                    Banner.Instance.ShowBanner();
                } else {//黑白包模式
                    if (Banner.cityIswhite) {//黑包
                        Banner.Instance.ShowVideo(() => { });
                        Banner.Instance.ShowNativeAd();
                        Banner.Instance.ShowBanner();
                    } else {//白包
                        Banner.Instance.ShowNativeAd();
                        Banner.Instance.ShowBanner();
                    }
                }
            });
        }
    }

    LoadPrefab(path: string, callback) {
        cc.resources.load("Prefabs/" + path, cc.Prefab, (err, res: cc.Prefab) => {
            if (err) console.log(err);
            callback(res);
        })
    }
    LoadSpriteFrame(bundle: string, path: string, callback) {
        BundleManager.GetBundle(bundle).load(path, cc.SpriteFrame, (err, res: cc.SpriteFrame) => {
            if (err) console.log(err);
            callback(res);
        })
    }

    GetEnumKey(Em: any, value) {
        for (const key in Em) {
            if (Em[key] === value) {
                return key;
            }
        } return undefined;
    }

    //打开暂停界面
    Open_PausePanel() {
        if (!Banner.IsBlackWhite) {//正常包模式
            Banner.Instance.ShowNativeAd();
        } else {//黑白包模式
            if (Banner.cityIswhite) {//黑包

            } else {//白包

            }
        }
        // GameManager.GetUINode("暂停界面").active = true;

    }
    //退出暂停界面
    Exit_PausePanel() {

    }
    //点击提示按钮
    OnTipClick() {
        Banner.Instance.ShowVideo(() => {
        })
    }

    //开始游戏
    Play() {
        this.MainUI.active = false;
        this.GameUI.active = true;
        this.schedule(() => {
            this.secondincident();
        }, 1)
        this.schedule(() => {
            this.Fivesecondincident();
        }, 5)
        this.ShowGuide();
    }

    /** 新手引导 */
    ShowGuide() {
        if (GameManager.IsGuided) return;
        let guide = this.GameUI.getChildByName("开局引导").children[this.GuideIndex];
        guide.active = true;
        cc.tween(guide.children[0])
            .by(0.5, { position: cc.v3(0, -30) })
            .by(0.5, { position: cc.v3(0, 30) })
            .union()
            .repeat(3)
            .call(() => { guide.children[0].getComponent(cc.Sprite).enabled = false; guide.children[0].children[0].active = false })
            .delay(0.5)
            .call(() => {
                this.GuideIndex++;
                guide = this.GameUI.getChildByName("开局引导").children[this.GuideIndex];
                guide.active = true;
                cc.tween(guide.children[0])
                    .by(0.5, { position: cc.v3(0, 30) })
                    .by(0.5, { position: cc.v3(0, -30) })
                    .union()
                    .repeat(3)
                    .call(() => { guide.children[0].getComponent(cc.Sprite).enabled = false; guide.children[0].children[0].active = false })
                    .delay(0.5)
                    .call(() => {
                        this.GuideIndex++;
                        guide = this.GameUI.getChildByName("开局引导").children[this.GuideIndex];
                        this.GameUI.getChildByName("开局引导").getChildByName("描述").active = true;
                        guide.active = true;
                        cc.tween(guide)
                            .by(1, { angle: -100 })
                            .delay(0.5)
                            .call(() => {
                                guide.angle = -90;
                                GameManager.IsGuided = true;
                            })
                            .union()
                            .repeat(3)
                            .call(() => { this.GameUI.getChildByName("开局引导").getChildByName("描述").active = false; guide.active = false; })
                            .start()
                    })
                    .start()
            })
            .start()
    }



    //缩放
    isZoomed: boolean = false;
    Zoom() {
        if (this.isZoomed == null) return;
        if (this.isZoomed) {
            this.isZoomed = null;
            cc.tween(this.mainCamera)
                .to(0.3, { zoomRatio: 1 })
                .call(() => { this.isZoomed = false; })
                .start()
        }
        else {
            this.isZoomed = null;
            cc.tween(this.mainCamera)
                .to(0.3, { zoomRatio: 1.5 })
                .call(() => { this.isZoomed = true; })
                .start()
        }
    }

    /**
     * 修改货币
     * @param num 修改货币值
     */
    C_Money(num: number) {
        GameData.Instance.Money += num;
        this.GameUI.getChildByName("Energy").getComponentInChildren(cc.Label).string = GameData.Instance.Money.toFixed(0);
        this.JudgeMoneyEnough();
    }
    //修改污染值
    C_GameScore() {
        GameData.Instance.GameScore = GameData.Getcontaminate();
        //如果污染值达到阈值，产生小人等
        for (let i = 1; i < 5; i++) {
            let max = GameData.Get_thresholdvalue(i);
            let current = GameData.Instance.EarthOuts[i].length;
            if (current < max) {
                this.AddEarthOut(i, max - current);
            }
            if (current > max) {
                this.SubEarthOut(i, current - max);
            }
        }
        if (GameData.Get_thresholdvalue(0) >= 10) {
            this.GameOver(false);
        }
    }

    /**
     * 添加地球产出
     * @param eo 产出的类型
     * @param num 产出的数量，不填默认产出1个
     */
    AddEarthOut(eo: EarthOut, num: number = 1) {
        for (let i = 0; i < num; i++) {
            this.LoadPrefab(this.GetEnumKey(EarthOut, eo), (pre) => {
                let out = cc.instantiate(pre);
                out.setParent(this.EarthNode);
                GameData.Instance.EarthOuts[eo].push(out);
            })
        }
    }

    /**
     * 删减地球产出
     * @param eo 删减的类型
     * @param num 需要删减的数量，不填默认删减1个
     */
    SubEarthOut(eo: EarthOut, num: number = 1) {
        for (let i = 0; i < num; i++) {
            if (GameData.Instance.EarthOuts[eo].length > 0) {
                let out = GameData.Instance.EarthOuts[eo].shift();
                out.destroy();
            }
        }
    }

    /** 建筑选择 */
    BuildClicked(e: cc.Event) {
        console.log(e.target.name)
        this.plantMode = true;
        this.plantId = GameData.BuildName.indexOf(e.target.name);
        this.GameUI.getChildByName("Builds").active = false;
    }

    /** 判断金钱是否足够 */
    JudgeMoneyEnough() {
        for (let i of this.GameUI.getChildByName("Builds").children) {
            if (GameData.Instance.Money >= Number(i.children[0].name)) {
                i.color = cc.Color.WHITE;
                i.opacity = 255;
                i.getComponent(cc.Button).interactable = true;
            }
            else {
                i.color = cc.Color.RED;
                i.opacity = 120;
                i.getComponent(cc.Button).interactable = false;
            }
        }
    }
    /**
     * 种植房子
     * @param id 房子类型的id
     * @param index 种植所在的槽位
     */
    plant(id: number, index: number) {
        cc.resources.load("Prefabs/" + GameData.BuildName[id], cc.Prefab, (err, event) => {
            if (err) {
                console.log("没有找到预制体" + GameData.BuildName[id]);
                return;
            }
            let pre = cc.instantiate(event);
            this.EarthNode.children[index].removeAllChildren();
            pre.setParent(this.EarthNode.children[index]);
            pre.getComponent(Build).Duang();
            AudioManager.PlayEffect(GameData.BuildName[id]);
            GameData.Instance.NodeData[index] = id;
            this.C_Money(-GameData.BuildPrice[id]);
            GameData.Instance.increaseSpeed = GameData.Getproduction();
            this.C_GameScore();
            this.C_Earth(GameData.Get_thresholdvalue(EarthOut.Earth_earth));
        })
    }

    //获取点击位置id
    GetRotaTionId(e: cc.Touch): number {
        var dir = e.getLocation().sub(ZTool.GetWorldPosition(this.EarthNode));
        var rotation = 180 / Math.PI * Math.atan2(dir.y, dir.x);
        let raotation2 = Math.abs((rotation + 180));
        let id = Math.floor(raotation2 / 9) + 10;
        id += (Math.abs(Math.floor(this.EarthNode.angle / 9)))
        while (id < 0) {
            id += 40;
        }
        while (id >= 40) {
            id -= 40;
        }
        console.log("种植位置:" + id);
        return id;
    }
    //更改地球状态
    C_Earth(id: number) {
        this.Bg.color = GameData.BgColor[id];
        BundleManager.GetBundle("Texture").load("地球" + id, cc.SpriteFrame, (err, event) => {
            if (err) {
                console.log("地球图片不存在");
                return;
            }
            if (id < 10) {
                this.EarthNode.getComponent(cc.Sprite).spriteFrame = event;
            } else {
                this.scheduleOnce(() => {
                    this.EarthNode.getComponent(cc.Sprite).spriteFrame = event;
                }, 1.75)
            }
        })
        if (id == 3) {
            //修改背景音乐
            AudioManager.PlayMusic("前半段")
        }
        if (id == 4) {
            //修改背景音乐
            AudioManager.PlayMusic("后半段")
        }
    }
    /**生成闪电 */
    Createlightning() {
        let pre = this.Bg.getChildByName("云").children[ZTool.GetRandomInt(0, 12)].getChildByName("闪电");
        pre.active = true;
        pre.opacity = 0;
        cc.tween(pre)
            .to(0.1, { opacity: 255 })
            .delay(0.4)
            .to(0.1, { opacity: 0 })
            .to(0.1, { opacity: 255 })
            .delay(0.6)
            .to(0.5, { opacity: 0 })
            .call(() => { pre.active = false; })
            .start();
        AudioManager.PlayEffect("雷电");
    }

    //相机抖动
    Camera_shake(callback: Function) {
        let InitPoint = this.mainCamera.node.position;
        cc.tween(this.mainCamera.node)
            .to(0.05, { position: InitPoint.clone().add(cc.v3(30, 15)) })
            .to(0.05, { position: InitPoint.clone().add(cc.v3(-30, -15)) })
            .to(0.02, { position: InitPoint })
            .union()
            .repeat(15)
            .call(() => {
                callback();
            })
            .start();
    }

    //点击观看视屏
    OnVidoeClick() {
        Banner.Instance.ShowVideo(() => {
            GameData.Instance.increasemultiple++;
            this.GameUI.getChildByName("Energy").getChildByName("倍数").getComponent(cc.Label).string = "收集速度X" + GameData.Instance.increasemultiple;
        })
    }

    //点击返回
    OnReMainButton() {
        this.GameUI.getChildByName("退出界面").active = true;
    }
    //返回
    ReMain() {
        cc.director.loadScene("Game");
    }
    //继续游戏
    continue() {
        this.GameUI.getChildByName("退出界面").active = false;
    }
}
